<template>
  <div class="order-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <!-- 添加返回按钮 -->
      <button class="back-button" @click="goBack">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 16 16">
          <path fill-rule="evenodd" d="M12 8a.5.5 0 0 1-.5.5H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 7.5H11.5a.5.5 0 0 1 .5.5z"/>
        </svg>
      </button>
      <h2>订单管理</h2>
      <div class="header-decoration">
        <div class="decoration-circle"></div>
        <div class="decoration-circle"></div>
        <div class="decoration-circle"></div>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filters-card">
      <div class="filters">
        <div class="filter-group">
          <label>角色:</label>
          <select v-model="filters.role" @change="handleRoleChange">
            <option value="buyer">买家</option>
            <option value="seller">卖家</option>
          </select>
        </div>

        <div class="filter-group">
          <label>状态:</label>
          <select v-model="filters.status" @change="handleStatusChange">
            <option value="0">全部状态</option>
            <option value="1">待确认</option>
            <option value="2">进行中</option>
            <option value="3">已完成</option>
            <option value="4">已取消</option>
          </select>
        </div>

        <div class="filter-group search-group">
          <input
              type="text"
              v-model="filters.searchKeyword"
              placeholder="输入物品标题搜索"
              @keyup.enter="searchOrders"
          >
          <button @click="searchOrders" class="search-btn">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
              <path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/>
            </svg>
          </button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 订单列表 -->
    <div v-else class="orders-list">
      <div v-if="filteredOrders.length === 0" class="empty-state">
        <div class="empty-icon">
          <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="#90caf9" viewBox="0 0 16 16">
            <path d="M0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V2zm6 10a1 1 0 1 0 0 2h4a1 1 0 1 0 0-2H6z"/>
          </svg>
        </div>
        <p>暂无订单数据</p>
      </div>

      <div v-else class="order-cards">
        <div v-for="order in filteredOrders" :key="order.orderId" class="order-card">
          <div class="order-header">
            <span class="order-number">订单号: {{ order.orderNumber }}</span>
            <span class="order-status" :class="`status-${order.status}`">
              {{ statusMap[order.status] }}
            </span>
          </div>

          <div class="order-content">
            <h3 class="item-title">{{ order.title }}</h3>

            <div class="order-info">
              <div class="price">¥{{ order.price }}</div>
              <div v-if="order.rentDays" class="rent-days">{{ order.rentDays }}天</div>
            </div>

            <div class="user-info">
              <!-- 动态显示用户角色 -->
              <div v-if="order.buyerId === userId">
                <span class="info-label">卖家:</span> {{ order.sellerName }} ({{ order.sellerBuilding }}栋)
              </div>
              <div v-else>
                <span class="info-label">买家:</span> {{ order.buyerName }} ({{ order.buyerBuilding }}栋)
              </div>
            </div>

            <div class="dates">
              <div v-if="order.startDate"><span class="info-label">开始:</span> {{ formatDate(order.startDate) }}</div>
              <div v-if="order.endDate"><span class="info-label">结束:</span> {{ formatDate(order.endDate) }}</div>
            </div>
          </div>

          <div class="order-actions">
            <button @click="viewOrderDetail(order.orderId)" class="detail-btn">
              查看详情
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                <path fill-rule="evenodd" d="M1 8a.5.5 0 0 1 .5-.5h11.793l-3.147-3.146a.5.5 0 0 1 .708-.708l4 4a.5.5 0 0 1 0 .708l-4 4a.5.5 0 0 1-.708-.708L13.293 8.5H1.5A.5.5 0 0 1 1 8z"/>
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import axios from "@/utils/axios.ts";
import { ElMessage } from 'element-plus'

const router = useRouter()
const userId = ref(null)

// 订单数据
const orders = ref([])
const loading = ref(false)

// 筛选条件
const filters = reactive({
  role: 'buyer', // 默认查看买家订单
  status: '0',   // 0表示全部状态
  searchKeyword: ''
})

// 订单状态映射
const statusMap = {
  1: '待确认',
  2: '进行中',
  3: '已完成',
  4: '已取消'
}

// 添加返回方法
const goBack = () => {
  router.back(); // 返回上一页
}

// 计算属性：过滤后的订单
const filteredOrders = computed(() => {
  let result = orders.value

  // 只有在非搜索状态下才按角色过滤
  if (!filters.searchKeyword && filters.role && userId.value) {
    result = result.filter(order =>
        filters.role === 'buyer' ? order.buyerId === userId.value : order.sellerId === userId.value
    )
  }

  // 按状态过滤
  if (filters.status && filters.status !== '0') {
    const statusNum = parseInt(filters.status)
    result = result.filter(order => order.status === statusNum)
  }

  return result
})

// 获取用户信息
const fetchUserInfo = () => {
  return axios.post("/api/users/getUserInfo")
      .then(res => {
        userId.value = res.data.userId
        console.log("userId", userId.value)
        return userId.value
      })
      .catch(error => {
        console.error('获取用户信息失败:', error)
        ElMessage.error('获取用户信息失败')
        throw error
      })
}

// 获取订单列表
const fetchOrders = () => {
  loading.value = true
  console.log("身份：", filters.role)

  // 确保userId已获取
  if (!userId.value) {
    fetchUserInfo().then(() => {
      doFetchOrders()
    })
    return
  }

  doFetchOrders()
}

// 实际执行获取订单
const doFetchOrders = () => {
  axios.get(`/api/itemOrders/getOrders/${userId.value}/${filters.role}`)
      .then(response => {
        if (response.code === 200) {
          orders.value = response.data || []
          ElMessage.success(`获取到${orders.value.length}条订单`)
          console.log("全部订单：", orders.value)
        } else {
          ElMessage.error(response.msg || '获取订单失败')
        }
      })
      .catch(error => {
        console.error('获取订单失败:', error)
        ElMessage.error('获取订单失败')
      })
      .finally(() => {
        loading.value = false
      })
}

// 按状态筛选订单
const fetchOrdersByStatus = (status) => {
  loading.value = true

  // 确保userId已获取
  if (!userId.value) {
    fetchUserInfo().then(() => {
      doFetchOrdersByStatus(status)
    })
    return
  }

  doFetchOrdersByStatus(status)
}

// 实际执行按状态获取订单
const doFetchOrdersByStatus = (status) => {
  axios.get(`/api/itemOrders/getOrders/${userId.value}/${filters.role}/${status}`)
      .then(response => {
        if (response.code === 200) {
          orders.value = response.data || []
          ElMessage.success(`获取到${orders.value.length}条订单`)
          console.log("状态:" + status + "数据：", orders.value)
        } else {
          ElMessage.error(response.msg || '获取订单失败')
        }
      })
      .catch(error => {
        console.error('获取订单失败:', error)
        ElMessage.error('获取订单失败')
      })
      .finally(() => {
        loading.value = false
      })
}

// 搜索订单
const searchOrders = () => {
  if (!filters.searchKeyword.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  loading.value = true

  // 确保userId已获取
  if (!userId.value) {
    fetchUserInfo().then(() => {
      doSearchOrders()
    })
    return
  }

  doSearchOrders()
}

// 实际执行搜索订单
const doSearchOrders = () => {
  const encodedTitle = encodeURIComponent(filters.searchKeyword)
  axios.get(`/api/itemOrders/orders/byTitle/${userId.value}/${encodedTitle}`)
      .then(response => {
        if (response.code === 200) {
          orders.value = response.data || []
          ElMessage.success(`找到${orders.value.length}条相关订单`)
          console.log("搜索内容：", orders.value)
        } else {
          ElMessage.error(response.msg || '搜索订单失败')
        }
      })
      .catch(error => {
        console.error('搜索订单失败:', error)
        ElMessage.error('搜索订单失败')
      })
      .finally(() => {
        loading.value = false
      })
}

// 查看订单详情
const viewOrderDetail = (orderId) => {
  let id = orderId;
  router.push(`/myOrderDetail/${id}`)
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 处理角色变更
const handleRoleChange = () => {
  // 清空搜索关键词
  filters.searchKeyword = ''

  if (filters.status === '0') {
    fetchOrders()
  } else {
    fetchOrdersByStatus(parseInt(filters.status))
  }
}

// 处理状态变更
const handleStatusChange = () => {
  if (filters.status === '0') {
    fetchOrders()
  } else {
    fetchOrdersByStatus(parseInt(filters.status))
  }
}

// 监听搜索关键词变化
watch(() => filters.searchKeyword, (newValue) => {
  if (!newValue) {
    // 搜索关键词为空时，重新获取订单列表
    if (filters.status === '0') {
      fetchOrders()
    } else {
      fetchOrdersByStatus(parseInt(filters.status))
    }
  }
})

// 初始化
onMounted(() => {
  fetchUserInfo().then(() => {
    fetchOrders()
  })
})
</script>

<style scoped>
/* 全局样式 */
.order-management {
  padding: 20px;
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f8ff 100%);
  min-height: 100vh;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 120, 242, 0.1);
}

.back-button {
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #1890ff;
  border-radius: 50%;
  transition: all 0.3s;
}

.back-button:hover {
  background-color: #e6f7ff;
}

.back-button svg {
  width: 20px;
  height: 20px;
}

.page-header h2 {
  color: #1890ff;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.header-decoration {
  display: flex;
  gap: 8px;
}

.decoration-circle {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: linear-gradient(135deg, #36cfc9 0%, #1890ff 100%);
}

.decoration-circle:nth-child(2) {
  background: linear-gradient(135deg, #bae7ff 0%, #69c0ff 100%);
}

.decoration-circle:nth-child(3) {
  background: linear-gradient(135deg, #87e8de 0%, #36cfc9 100%);
}

/* 筛选卡片 */
.filters-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 4px 12px rgba(0, 120, 242, 0.1);
}

.filters {
  display: flex;
  gap: 20px;
  margin-bottom: 0;
  flex-wrap: wrap;
  align-items: center;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-weight: 600;
  color: #262626;
  font-size: 14px;
}

.filter-group select {
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  background: white;
  color: #262626;
  font-size: 14px;
  outline: none;
  transition: all 0.3s;
}

.filter-group select:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.search-group {
  position: relative;
  display: flex;
  align-items: center;
}

.search-group input {
  padding: 8px 40px 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  font-size: 14px;
  outline: none;
  transition: all 0.3s;
  width: 200px;
}

.search-group input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.search-btn {
  position: absolute;
  right: 8px;
  background: none;
  border: none;
  color: #1890ff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 加载状态 */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 120, 242, 0.1);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #e6f7ff;
  border-top: 3px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading p {
  color: #595959;
  font-size: 16px;
  margin: 0;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 120, 242, 0.1);
}

.empty-icon {
  margin-bottom: 16px;
}

.empty-state p {
  color: #595959;
  font-size: 16px;
  margin: 0;
}

/* 订单卡片 */
.order-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.order-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 120, 242, 0.1);
  transition: all 0.3s;
  border: 1px solid transparent;
}

.order-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(24, 144, 255, 0.15);
  border-color: #bae7ff;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.order-number {
  font-size: 14px;
  color: #8c8c8c;
}

.order-status {
  padding: 4px 8px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.status-1 {
  background-color: #fff7e6;
  color: #fa8c16;
}

.status-2 {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-3 {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-4 {
  background-color: #fff1f0;
  color: #f5222d;
}

.order-content {
  margin-bottom: 16px;
}

.item-title {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.order-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.price {
  font-weight: 600;
  color: #f5222d;
  font-size: 18px;
}

.rent-days {
  padding: 4px 8px;
  background: #e6f7ff;
  color: #1890ff;
  border-radius: 4px;
  font-size: 12px;
}

.user-info, .dates {
  margin-bottom: 8px;
  font-size: 14px;
  color: #595959;
}

.info-label {
  font-weight: 500;
  color: #262626;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
}

.detail-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #36cfc9 0%, #1890ff 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s;
}

.detail-btn:hover {
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
  transform: translateY(-2px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filters {
    flex-direction: column;
    align-items: stretch;
  }

  .filter-group {
    justify-content: space-between;
  }

  .search-group input {
    width: 100%;
  }

  .order-cards {
    grid-template-columns: 1fr;
  }
}
</style>